package com.imooc.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.imooc.dto.FileInfo;
import com.imooc.service.FileService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("file")
public class FileController {
	
	private static final String folder = "D:\\文件\\测试";
	
	@Autowired
	private FileService fileService;

	@PostMapping
	@ApiOperation(value = "uploadFile() 上传文件")
	public FileInfo uploadFile(@ApiParam(value="文件") MultipartFile file) throws IllegalStateException, IOException {
		System.out.println("【文件上传】文件名："+file.getName());
		System.out.println("【文件上传】原始文件名："+file.getOriginalFilename());
		System.out.println("【文件上传】文件大小："+file.getSize());
		return fileService.uploadFile(file);
	}
	
	@GetMapping("/{id}")
	@ApiOperation(value = "downloadFile() 下载文件")
	public void downloadFile(@ApiParam(value="文件ID（时间戳）") @PathVariable("id") String id, HttpServletResponse response) {
		try(
				InputStream in = new FileInputStream(new File(folder, id+".txt"));
				OutputStream out = response.getOutputStream();
				) {
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachment;filename="+new String("日志.txt".getBytes("gb2312"), "ISO8859-1"));
			IOUtils.copy(in, out);
			out.flush();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}
